package com.example.actionsignin.utils;

import android.content.Context;
import android.util.Log;

import com.example.actionsignin.entity.FaceEntity;
import com.example.actionsignin.http.FaceHttpUtil;
import com.example.actionsignin.http.HttpUtil;

import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 人脸识别
 * Created by 旭 on 2017/11/6/006.
 */

public class FaceUtil {

    private static final String TAG = "FaceUtil";
    private Context mContext;
    private OnFaceListener mOnFaceListener;

    public FaceUtil(Context context){
        this.mContext = context;
    }

    public void sendFaceRequest(String path,RequestBody body){

        String key = "MjuQtsjSuabIWqhPGlicajQtpvCYixVV";
        String secret = "uGNIhXI-uvRj5hUA1AHQT9peBhaV9pKU";

        FaceHttpUtil.sendFace().face(key,secret,path,body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<FaceEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {
//                        Log.d(TAG, "onSubscribe: ");
                    }

                    @Override
                    public void onNext(FaceEntity faceEntity) {
                        Log.d(TAG, "onNext: " + faceEntity.toString());

                        if (faceEntity.getConfidence() >= 80)
                        {
                            ToastUtil.INSTANCE(mContext,"识别成功");
                            mOnFaceListener.onFaceOk();
                        }else if (faceEntity.getThresholds() == null)
                        {
                            ToastUtil.INSTANCE(mContext,"未检测到人脸");
                        } else {
                            ToastUtil.INSTANCE(mContext,"识别失败");
                            mOnFaceListener.onFaceCancel();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d(TAG, "onError: " + e);
//                        mOnFaceListener.onFaceCancel();
                        ToastUtil.INSTANCE(mContext,"网络出现波动");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void setListener(OnFaceListener onFaceListener){
        this.mOnFaceListener = onFaceListener;
    }

    public interface OnFaceListener{
        void onFaceOk();
        void onFaceCancel();
    }
}
